//
//  61. 旋转链表.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/9/6.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution61 {
    // 旋转链表
    // 1. 先采取快慢指针找到后面的节点
    // 2. 然后后面的链表链接上前面链表的尾部
    func rotateRight(_ head: ListNode?, _ k: Int) -> ListNode? {
        if head == nil {
            return head
        }
        var slow = head
        var fast = head
        
        var preSlow: ListNode?
        var preFast: ListNode?
        
        var m = k % linkCount(head)
        if m == 0 {
            return slow
        }
        while fast != nil {
            if m <= 0 {
                preSlow = slow
                slow = slow?.next
            }
            m -= 1
            preFast = fast
            fast = fast?.next
        }
        preSlow?.next = nil
        preFast?.next = head

        return slow
    }
    func linkCount(_ head: ListNode?) -> Int {
        var p = head
        var count = 0
        while p != nil {
            p = p?.next
            count += 1
        }
        return count
    }
    static func test() {
        let solution = Solution61()
//        let node1 = ListNode(1)
//        let node2 = ListNode(2)
//        let node3 = ListNode(3)
//        let node4 = ListNode(4)
//        let node5 = ListNode(5)
//
//        node1.next = node2
//        node2.next = node3
//        node3.next = node4
//        node4.next = node5
        
        let node2 = ListNode(1)
        
        let result =  solution.rotateRight(node2, 0)
        print(result)
    }
}
